package com.pig4cloud.pigx.wallet.websocket.subscribe;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import com.pig4cloud.pigx.common.websocket.holder.SessionKeyGenerator;
import com.pig4cloud.pigx.wallet.constant.NotificationEnum;
import com.pig4cloud.pigx.wallet.entity.Notification;
import com.pig4cloud.pigx.wallet.service.AccountService;
import com.pig4cloud.pigx.wallet.service.NotificationService;
import com.pig4cloud.pigx.wallet.vo.AbstractTopicVO;
import com.pig4cloud.pigx.wallet.websocket.WalletNoticeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 */
@Slf4j
@Component
public class WalletNoticeHandler extends DataListAbstractTopic {

	private final AccountService accountService;

	private final SessionKeyGenerator sessionKeyGenerator;

	protected String TOPICNAME = "walletNotice";

	public WalletNoticeHandler(AccountService accountService, SessionKeyGenerator sessionKeyGenerator, CommonUtil commonUtil) {
		this.accountService = accountService;
		this.sessionKeyGenerator = sessionKeyGenerator;
		init();
	}

	private void init() {
		wsPush();
	}

	private void wsPush() {
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.scheduleAtFixedRate(() -> {
			try {
				for (Map.Entry<WebSocketSession, AbstractTopicVO> entry : subList.entrySet()) {

					if (entry.getKey().isOpen() == false) {
						continue;
					}
					try {
						Object userId = sessionKeyGenerator.sessionKey(entry.getKey());
						List<WalletNoticeVo> list = accountService.getWalletNotice((String) userId);
						// 发送消息
						entry.getKey().sendMessage(getTextMessage(entry.getValue().getDataList(), list));
					} catch (Exception ex) {
						ex.printStackTrace();
						log.info("push last price err:" + ex.getMessage());
					}

				}
				Thread.sleep(3000);
			} catch (Exception e) {
				e.printStackTrace();
				log.info("push ranking err:" + e.getMessage());
			}

		}, 0, 2000, TimeUnit.MILLISECONDS);
	}
}
